package com.ujoku.controller;

import com.labillusion.core.platform.web.rest.RESTController;
import com.labillusion.core.platform.web.rest.exception.InvalidRequestException;
import com.labillusion.core.util.SequenceNumUtils;
import com.labillusion.core.util.UUIDUtils;
import com.ujoku.context.ActionContext;
import com.ujoku.context.constants.MessageConstants;
import com.ujoku.domain.*;
import com.ujoku.interceptor.LoginRequired;
import com.ujoku.request.AddressForm;
import com.ujoku.request.ApplyForm;
import com.ujoku.service.AddressService;
import com.ujoku.service.ApplyService;
import com.ujoku.service.MessageService;
import com.ujoku.service.RegionService;
import com.ujoku.view.domain.AddressView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Greg on 14-10-25.
 */
@RestController
public class ApplyController extends RESTController {

    @Autowired
    public ApplyService service;

    @Autowired
    public MessageService messageService;

    @Autowired
    private ActionContext actionContext;

    @RequestMapping(value="/apply", method = RequestMethod.POST)
    @ResponseBody
    @LoginRequired
    public String checkApplication(@Valid @RequestBody ApplyForm form){

        Member member = actionContext.getMember();

        Map<String,Object> query = new HashMap<>();
        query.put("fromMemberId" , member.getUser_id());
        query.put("toMemberId" , form.getToMemberId());
        query.put("listItemId" , form.getListItemId());

        Apply apply = (Apply)service.selectOne(query);
        Message message = messageService.bulid(MessageConstants.APPLY, form.getToMemberId(), new String[]{member.getUser_name(), form.getGoodsName()});
        if(apply == null){
            apply = new Apply();
            BeanUtils.copyProperties(form,apply);
            apply.setId(SequenceNumUtils.generateNum());
            apply.setFromMemberId(member.getUser_id());
            service.insert(apply);

            messageService.insert(message);
        }else{
            Date lastTime = apply.getUpdateTime();
            Date Now = new Date();
            long lag = Now.getTime() - lastTime.getTime();
            if(lag > (1000 * 60 * 60 * 24 *3)){
                service.update(apply);
                messageService.insert(message);
            }else{
                throw new InvalidRequestException("still applying for purchase");
            }
        }

        return "successfully";
    }


}
